<template>
  <!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
  <a-drawer
      v-model:open="visible"
      ref="employeeDetailModalRef"
      class="edit-drawer modal-fixed-bottom"
      root-class-name="root-customer-drawer"
      width="800px"
      :closable="false"
      @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>
    <a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
            @finish="onSubmit"
    >
      <a-form-item :label="$t('self.user.modal.firstName')" name="firstName">
        <a-input allow-clear v-model:value="formState.firstName" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.user.modal.lastName')" name="lastName">
        <a-input allow-clear v-model:value="formState.lastName" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.user.tips2')" name="phone">
        <a-input allow-clear v-model:value="formState.phone" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.user.tips9')" name="email">
        <a-input allow-clear v-model:value="formState.email" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.user.modal.country')" name="country">
        <a-input allow-clear v-model:value="formState.country" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.user.modal.city')" name="city">
        <a-input allow-clear v-model:value="formState.city" placeholder="" />
      </a-form-item>



      <a-form-item :label="$t('self.systemUser.modal.col8')" name="userNo">
        <a-input allow-clear v-model:value="formState.userNo" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.systemUser.modal.col9')" name="password">
        <a-input allow-clear v-model:value="formState.password" placeholder="" />
      </a-form-item>
      <a-form-item label="Vehicle Type" name="vehicleType">
        <a-select v-model:value="formState.vehicleType" :options="vehicleTypeOptions" :placeholder="$t('self.pleaseChoose')" />
      </a-form-item>

      <a-form-item label="Vehicle Chassis" name="VehicleChassis">
        <a-input allow-clear v-model:value="formState.VehicleChassis" placeholder="" />
      </a-form-item>
      <a-form-item label="Plate Number" name="plateNumber">
        <a-input allow-clear v-model:value="formState.plateNumber" placeholder="" />
      </a-form-item>
      <a-form-item label="Color" name="color">
        <a-input allow-clear v-model:value="formState.color" placeholder="" />
      </a-form-item>
      <a-form-item label="Brand Model" name="brandModel">
        <a-input allow-clear v-model:value="formState.brandModel" placeholder="" />
      </a-form-item>

      <a-form-item :label="$t('self.user.modal.col14')" name="orgId">
        <a-select v-model:value="formState.orgId" :options="orgOptions" 
        :fieldNames="{label: 'orgName',value: 'id'}" 
        :placeholder="$t('self.pleaseChoose')" @change="onChangeOrg" />
      </a-form-item>





      <a-form-item label="Keyfob Type" name="KeyfobType">
        <a-input allow-clear v-model:value="formState.KeyfobType" placeholder="" />
      </a-form-item>
      <a-form-item label="Keyfob Color" name="keyfobColor">
        <a-input allow-clear v-model:value="formState.keyfobColor" placeholder="" />
      </a-form-item>
      <a-form-item label="Assign Keyfob" name="assignKeyfob">
        <a-input allow-clear v-model:value="formState.assignKeyfob" placeholder="" />
      </a-form-item>
      <a-form-item label="Assign UUID" name="assignUuid">
        <a-input allow-clear v-model:value="formState.assignUuid" placeholder="" />
      </a-form-item>
<!-- 
      <a-form-item name="Country Authorize" :label="$t('self.stationMap.africaCountry')" >
        <a-select allow-clear v-model:value="formState.area" 
        :options="africaCountryOptions"   :field-names="{ label: 'display', value: 'value' }"  @change="handleAfricaCountryChange"
        :placeholder="$t('self.pleaseChoose')">
        </a-select>
      </a-form-item> -->

      <!-- <a-form-item label="userNo" name="userNo">
        <a-input allow-clear v-model:value="formState.userNo" placeholder="" />
      </a-form-item> -->
      <a-form-item label="Account Status" name="userStatus">
        <a-select v-model:value="formState.userStatus" :options="[
          { label: 'Active', value: 1 },
          { label: 'Inactive', value: 0 },
          { label: 'Blocked', value: 2 },
          { label: 'Deleted', value: 3 }
        ]" :placeholder="$t('self.pleaseChoose')" />
      </a-form-item>


      <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
        <a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
        <a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
      </div>

    </a-form>
  </a-drawer>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import chooseAreaForLocal from '@/components/choose/choose-area-for-local.vue'
import { mainStore } from '@/stores/mainStore'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $T = proxy.$t
const $API = proxy.$API
const useMainStore = mainStore()

const emit = defineEmits(['close','ok'])

const visible = ref(false)
// 模式，add新增，show查看，edit编辑
const mode = ref('add')
const detail = ref({})
const labelCol = {
  style: {
    width: '200px',
  },
};
const wrapperCol = {
  span: 16,
};
const title = ref('')
const formState = ref({
  firstName: '',
  lastName: '',
  phone: '',
  password: '',
  email: '',
  country: '',
  city: '',
  lang: '',
  orgId: null,
  // orgName: '',
  vehicleType: '',
  authorizedCountryCode: null,
  VehicleChassis: '',
  plateNumber: '',
  color: '',
  brandModel: '',
  operator:'',
  KeyfobType: '',
  keyfobColor: '',
  assignUuid: '',
  assignKeyfob: '',
  userNo: '',
  userStatus: '',
  // area:''
})
const areaArr = ref([])
const orgOptions = ref([])
const vehicleTypeOptions = ref([
  { label: 'E-Motorcycle', value: 'E-Motorcycle' },
  { label: 'E-Car', value: 'E-Car' },
  { label: 'E-Van', value: 'E-Van' },
  { label: 'E-Bus', value: 'E-Bus' },
])
import cityData from '@/config/data.js'
import dayjs from 'dayjs'
const countryAuthorizeOptions = ref([])
const cityRaw =  cityData.cityRaw
const formRules = ref({
  firstName: [{required: true,message: $T('self.pleaseInput') + $T('self.user.modal.firstName'),trigger: 'change'}],
  lastName: [{required: true,message: $T('self.pleaseInput') + $T('self.user.modal.lastName'),trigger: 'change'}],
  phone: [{required: true,message: $T('self.pleaseInput') + $T('self.user.tips2'),trigger: 'change'}],
  password: [{required: true,message: $T('self.pleaseInput') + $T('self.user.modal.col12'),trigger: 'change'}],
  country: [{required: true,message: $T('self.pleaseInput') + $T('self.user.tips9'),trigger: 'change'}],
  orgId: [{required: true,message: $T('self.user.modal.col14'),trigger: 'change'}],

  vehicleType: [{required: true, message: $T('self.pleaseInput') + 'VehicleChassis', trigger: 'change'}],
  plateNumber: [{required: true, message: $T('self.pleaseInput') + 'plateNumber', trigger: 'change'}],
  color: [{required: true, message: $T('self.pleaseInput') + 'color', trigger: 'change'}],
  // countryAuthorize: [{required: true, message: $T('self.pleaseInput') + 'brandModel', trigger: 'change'}],
  KeyfobType: [{required: true, message: $T('self.pleaseInput') + 'KeyfobType', trigger: 'change'}],
  keyfobColor: [{required: true, message: $T('self.pleaseInput') + 'keyfobColor', trigger: 'change'}],
  assignUuid: [{required: true, message: $T('self.pleaseInput') + 'assignUuid', trigger: 'change'}],
  assignKeyfob: [{required: true, message: $T('self.pleaseInput') + 'assignKeyfob', trigger: 'change'}],
  userNo: [{required: true, message: $T('self.pleaseInput') + 'userNo', trigger: 'change'}],
  userStatus: [{required: true, message: $T('self.pleaseChoose') + 'userStatus', trigger: 'change'}],
  city: [{required: true,message: $T('self.pleaseChoose') + $T('self.user.modal.city'),trigger: 'change'}]
})
	// 1. 非洲国家
	const africaCountryOptions = cityData.africaCountryOptions.map(item => ({
		...item,
		display: `${item.labelCn} / ${item.labelEn}` + (item.labelRW ? ` / ${item.labelRW}` : '')
	}));
  	// 修改国家变更事件，保存国家名称
	const handleAfricaCountryChange = async (countryCode) => {
		formState.value.countryAuthorize = countryCode;

		const selectedCountry = africaCountryOptions.find(item => item.value === countryCode);
		// formState.value.country = selectedCountry ? selectedCountry.labelCn : null;
	};

onMounted(async () => {
  orgOptions.value = await proxy.getOrgSelectList(true)
  console.log('onMounted===',orgOptions.value)
})

// const handleChangeArea = (area) => {
//   // formState.value.stationProvince = area[0]
//   formState.value.country = area[0]
//   formState.value.city = area[1]
// }

const onChangeOrg = (value, option) => {
  // formState.orgName = option.orgName
  formState.value.operator = option.orgName; 
}
const onSubmit = (values) => {
  console.log(formState.value)
  const params = { ...formState.value }
  // console.log('提交的operator值：', params.operator);  
  if(useMainStore.lang === 'zh-cn'){
    // 中文
    params.lang = 'cn'
  }else if(useMainStore.lang === 'en-us') {
    // 英文
    params.lang = 'en'
  }else{
    params.lang = 'rwd'
  }

  $API.backend.user.add.post(params).then(res => {
    onReset()
    visible.value = false
    emit('ok')
  }).catch(err => {
    message.error(err.msg || $T('self.message.error'))
    console.log('添加用户失败', err)
  })
  // console.log('submit!', values);
};

const onReset = () => {
  // 清空内容
  formState.value = {
    firstName: '',
    lastName: '',
    phone: '',
    password: '',
    email: '',
    country: '',
    city: '',
    lang: '',
    orgId: null,
    orgName: '',
    vehicleType: '',

  VehicleChassis: '',
  operator:'',
  plateNumber: '',
  color: '',
  brandModel: '',
  KeyfobType: '',
  keyfobColor: '',
  assignUuid: '',
  assignKeyfob: '',
  userNo: '',
  userStatus: ''
  }
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const add = () => {
  mode.value = 'add'
  visible.value = true
  title.value = $T('self.user.modal.title1')
}

// const edit = (record) => {
//   mode.value = 'edit'
//   visible.value = true
//   formState.value = record
//   title.value = $T('self.user.modal.title2') + '：' + formState.value.userName
//   // detail.value = record
//   // $TOOL.array.cloneExistKey(formState.value, detail.value)
//   // console.log(formState.value)
// }
const edit = (record) => {
    mode.value = 'edit'
  visible.value = true
  // formState.value = record
  title.value = $T('self.user.modal.title2') + '：' + formState.value.userName
  formState.value = {
    ...record
    // VehicleChassis: record.VehicleChassis || '',
    // operator: record.operator || '',
    // plateNumber: record.plateNumber || '',
    // color: record.color || '',
    // brandModel: record.brandModel || '',
    // KeyfobType: record.KeyfobType || '',
    // keyfobColor: record.keyfobColor || '',
    // assignUuid: record.assignUuid || '',
    // assignKeyfob: record.assignKeyfob || '',
    // userNo: record.userNo || '',
    // userStatus: record.userStatus || ''
  }
}
// 子组件中要通过defineExpose将方法暴露给父组件
defineExpose({
  add,
  edit,
})
</script>

<style lang="scss" scoped>
.edit-drawer {
  position: relative;
  .closeable {
    @include closeable;
  }
}
</style>
